import { Component, OnInit, TemplateRef } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';

@Component({
  selector: 'nz-table-list-header',
  templateUrl: './nz-table-list.component.html',
  styles  : []
})
export class NzTableListComponent implements OnInit {
  validateForm: FormGroup;
  pageIndex = 1;
  pageSize = 10;
  total = 1;
  loading = true;

  allChecked = false;
  indeterminate = false;
  displayData: Array<{ name: string; age: number; address: string; checked: boolean,disabled: boolean }> = [];
  dataSet = [];
  checkedNumber = 0;
  disabledButton = true;
  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };

  selectedRows: any[] = [];

  constructor(
    public msg: NzMessageService,
    private fb: FormBuilder,
    private modalSrv: NzModalService,
  ) {}

  ngOnInit(): void {
    this.loading = false;
    for (let i = 0; i < 100; i++) {
      this.dataSet.push({
        name   : `Edward King ${i}`,
        age    : 32,
        address: `London, Park Lane no. ${i}`,
        checked : false
      });
    }

    this.validateForm = this.fb.group({
      appName            : [ null, [  Validators.required ] ],
      description        : [ null, [ Validators.required ] ],
    });
  }

  currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
    this.displayData = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    const allChecked = this.displayData.filter(value => !value.disabled).every(value => value.checked === true);
    const allUnChecked = this.displayData.filter(value => !value.disabled).every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
    this.disabledButton = !this.dataSet.some(value => value.checked);
    this.checkedNumber = this.dataSet.filter(value => value.checked).length;
  }

  checkAll(value: boolean): void {
    this.displayData.forEach(data => {
      if (!data.disabled) {
        data.checked = value;
      }
    });
    this.refreshStatus();
  }

  deleteRow(name: String){
    this.msg.success('删除成功');
  }

  edit(name: String){
    this.msg.success("编辑中");
  }

  view(name: String){
    this.msg.success("view");
  }

  add(tpl: TemplateRef<{}>) {
    this.modalSrv.create({
      nzTitle: '新建应用',
      nzContent: tpl,
      nzOnOk: () => {
        this.loading = true;

        for (const i in this.validateForm.controls) {
          this.validateForm.controls[ i ].markAsDirty();
          this.validateForm.controls[ i ].updateValueAndValidity();
        }
        // form表单校验无效(未通过)
        if (this.validateForm.invalid) {
          this.msg.error(`表单校验不通过！！!`);
          this.loading = false;
          return false;
        }


      },
    });
  }
}
